# -*- coding: utf-8 -*-
'''
 Source file
 File name: config.py
 Creation date: 11-09-2011
 Author: dassier

'''

from ConfigParser import RawConfigParser
import os
import sys
from svi.core.logging import LogMsg

class Config(RawConfigParser):
    '''Class to access to configuration file (read/write)
    '''

    def __init__(self, filename):
        # Call RawConfigParser initialisation
        #super(Config, self).__init__()
        RawConfigParser.__init__(self)

        self._filename = filename
        self._msg = LogMsg()
        if not os.path.exists(filename):
            # Configuration file not found
            # Let's create one
            self._msg.info(u'Create new configuration file %s' % filename)
            try:
                self._f = open(filename, "w")
                self._f.write("# SVN Improvement configuration file\n")
                self._f.write("# Please do not edit manually\n")
                self._f.write("# this file is modified by 'svi' tool itself\n")
                self._f.write("\n")
            except IOError as strerror:
                # Error when reading file
                self._msg.error(u'%s: %s' % (self._filename, strerror))
                sys.exit(1)
            self._f.close()

            # Create basic sections
            self.add_section('core')
            self.set('core', 'main', '/dev/main')
            self.set('core', 'branches', '/dev/branches')
            self.set('core', 'tags', '/dev/tags')

            # Write to file
            self.save()

        else:
            # Configuration file exist, open it
            try:
                self._f = open(filename, "r")
                self.readfp(self._f)
            except IOError as strerror:
                # Error when reading file
                self._msg.error(u'%s: %s' % (self._filename, strerror))
                sys.exit(1)
            self._f.close()

    def save(self):
        ''' To save configuration to file
        '''
        try:
            self.write(open(self._filename, "w"))
        except IOError as strerror:
            # Error when writing file
            self._msg.error(u'%s: %s' % (self._filename, strerror))
            sys.exit(1)
        self._f.close()

